package response

import (
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gtime"
)

func getHeaderVersion(r *ghttp.Request) string {
	v := r.Header.Get("version")
	if len(v) < 1 {
		return "1.0.0"
	}
	return v
}

// 数据返回通用JSON数据结构
type JsonResponse struct {
	Code     int         `json:"code"    dc:"Error code"`
	Message  string      `json:"message" dc:"Error message"`
	Data     interface{} `json:"data"    dc:"Result data for certain request according API definition"`
	Version  string      `json:"version" dc:"API version"`
	Timespan string      `json:"timespan" dc:"request datetime"`
}

// 标准返回结果数据结构封装。
func Json(r *ghttp.Request, code int, message string, data ...interface{}) {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	if responseData == nil {
		responseData = g.Map{}
	}
	r.Response.WriteJson(JsonResponse{
		Code:     code,
		Message:  message,
		Version:  getHeaderVersion(r),
		Data:     responseData,
		Timespan: gtime.Now().Format("Y-m-d H:i:s"),
	})
}

// 返回JSON数据并退出当前HTTP执行函数。
func JsonExit(r *ghttp.Request, code int, msg string, data ...interface{}) {
	Json(r, code, msg, data...)
	r.Exit()
}

func SuccessByRequest(r *ghttp.Request) *JsonResponse {
	return JsonByAll(r, 0, "Success")
}

func SuccessByRequestMessage(r *ghttp.Request, message string) *JsonResponse {
	return JsonByAll(r, 0, message)
}
func SuccessByRequestMessageData(r *ghttp.Request, message string, data interface{}) *JsonResponse {
	return JsonByAll(r, 0, message, data)
}

func JsonByAll(r *ghttp.Request, code int, message string, data ...interface{}) *JsonResponse {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	versionStr := ""
	if r != nil {
		versionStr = getHeaderVersion(r)
	}
	if responseData == nil {
		responseData = gmap.Map{}
	}
	return &JsonResponse{
		Code:     code,
		Message:  message,
		Data:     responseData,
		Version:  versionStr,
		Timespan: gtime.Now().Format("Y-m-d H:i:s"),
	}
}

func FailByRequest(r *ghttp.Request) *JsonResponse {
	return FailByRequestMessage(r, "Error")
}
func FailByRequestMessage(r *ghttp.Request, message string) *JsonResponse {
	return JsonByAll(r, 1, message)
}

func FailByRequestMessageData(r *ghttp.Request, message string, data g.Map) *JsonResponse {
	return JsonByAll(r, 1, message, data)
}

func FailByRequestRateLimiter(r *ghttp.Request, messages ...string) *JsonResponse {
	msg := "操作太频繁，请休息一下"
	if len(messages) > 0 {
		msg = messages[0]
	}
	return JsonByAll(r, -99, msg)
}
